package com.academy.teacher;

import org.json.JSONException;
import org.json.JSONObject;

import com.academy.querystapp.R;
import com.academy.services.BaseService;
import com.academy.services.RequestMethod;
import com.academy.services.ResponseListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ReplyToStudentQueries extends Activity implements OnClickListener,ResponseListener
{
	TextView txtQuestion,txtAskedBy,txtVisitedCount;
	EditText edtAnswer;
	Button btnReply,btnReplyAndViewAll;
	String strQuestion,StrVisitingCount,strPostedID,strAskedBy,strAnswer;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reply_student_queries);
		initializeView();
		getIntentValues();
	}
	
	public void initializeView()
	{
		btnReply=(Button) findViewById(R.id.btnReply);
		btnReplyAndViewAll=(Button) findViewById(R.id.btnReplyAndViewAll);
		
		txtQuestion=(TextView) findViewById(R.id.txtQuestion);
		txtAskedBy=(TextView) findViewById(R.id.txtAskedBy);
		txtVisitedCount=(TextView) findViewById(R.id.txtVisited);
		
		edtAnswer=(EditText) findViewById(R.id.edtAnswer);
		
		btnReply.setOnClickListener(this);
		btnReplyAndViewAll.setOnClickListener(this);
	}

	public void getIntentValues()
	{
		if(getIntent().hasExtra("strPostedID"))
		{
			strPostedID=getIntent().getExtras().getString("strPostedID");
			System.out.println("strPostedID Id--> "+strPostedID);
		}
		
		if(getIntent().hasExtra("strQuestion"))
		{
			strQuestion=getIntent().getExtras().getString("strQuestion");
			System.out.println("strQuestion Id--> "+strQuestion);
		}
		
		if(getIntent().hasExtra("StrVisitingCount"))
		{
			StrVisitingCount=getIntent().getExtras().getString("StrVisitingCount");
			System.out.println("StrVisitingCount --> "+StrVisitingCount);
		}

		if(getIntent().hasExtra("strAskedBy"))
		{
			strAskedBy=getIntent().getExtras().getString("strAskedBy");
			System.out.println("strAskedBy --> "+strAskedBy);
		}
		
		txtQuestion.setText(strQuestion);
		txtVisitedCount.setText(StrVisitingCount);
		txtAskedBy.setText(strAskedBy);
	}
	
	@Override
	public void onClick(View v) 
	{
		if(v==btnReply)
		{
			postAnswer("0");
		}
		
		if(v==btnReplyAndViewAll)
		{
			postAnswer("1");
		}
		
	}
	
	private void parseResponse(String response)
	{
		if(response==null ||response.equals("null"))
		{
			Builder builder = new Builder(this);
			builder.setMessage("No Server Found!");
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int arg1)
				{	
					dialog.dismiss();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
		else
		{
			try 
			{ 
			
				JSONObject RootObject = new JSONObject(response);
				System.out.println("JSON Object "+RootObject.toString());
				final JSONObject queryResultObject = RootObject.getJSONObject("queryResult");
				System.out.println("queryResultObject "+queryResultObject.toString());
				
				System.out.println("Response "+queryResultObject.getString("status"));
				System.out.println("Value of response"+response);
				
				if(queryResultObject.getString("status").equals("false"))
				{
					Builder builder = new Builder(this);
					builder.setTitle("Post Answer");				
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
					{
						
					});
					AlertDialog alertDialog = builder.create();
					alertDialog.show();	 
				}
				else if(queryResultObject.getString("status").equals("true"))
				{
					Builder builder = new Builder(this);
					builder.setTitle("Post Answer");
					builder.setMessage(queryResultObject.getString("description"));
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int arg1)
						{				
							Intent i=new Intent(ReplyToStudentQueries.this,TeacherTabActivity.class);
							i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(i);
							finish();
							dialog.dismiss();
						}
					});
					AlertDialog alertDialog = builder.create();
					alertDialog.show();	 
					
				}
		  }
		  catch (JSONException e) 
		  {
			  e.printStackTrace();
		  } 
		}
	}

	public void postAnswer(final String ViewType)
	{
		strAnswer=edtAnswer.getText().toString().trim();
		if(strAnswer.equals(""))
		{
			
			Builder builder = new Builder(this);
			builder.setTitle("Post Answer");
			builder.setMessage("Please Enter the answer!");
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int arg1)
				{	
					dialog.dismiss();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
		else
		{
			BaseService baseService = new BaseService(this,this,RequestMethod.GET);//();
			baseService.addParam(getString(R.string.PostID_param), strPostedID);
			baseService.addParam(getString(R.string.Answer_param), edtAnswer.getText().toString().trim());
			baseService.addParam(getString(R.string.ViewPost_param),ViewType);

			baseService.addParam(getString(R.string.userType_Param),"ReplyPostQuery");
			baseService.execute(getString(R.string.answerPostedURL));
					        	
		}

	}
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {

	    View v = getCurrentFocus();
	    boolean ret = super.dispatchTouchEvent(event);

	    if (v instanceof EditText) {
	        View w = getCurrentFocus();
	        int scrcoords[] = new int[2];
	        w.getLocationOnScreen(scrcoords);
	        float x = event.getRawX() + w.getLeft() - scrcoords[0];
	        float y = event.getRawY() + w.getTop() - scrcoords[1];

	        Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
	        if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 

	            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
	        }
	    }
	return ret;
	}

	@Override
	public void onServiceCompleted(String response, String requestURL) {
		parseResponse(response);
		
	}

	@Override
	public void onServiceFailed(String exception, String requestURL) {
		// TODO Auto-generated method stub
		
	}

}


